﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.DataAccess.IRepositories;
using System.ComponentModel.Composition;

namespace Core.DataAccess.Repositories
{
    [Export(typeof(IRatingRepository))]
    public class RatingRepository : IRatingRepository
    {
        private Connection conn;

        public RatingRepository()
        {
            conn = new Connection();
        }

        public bool SaveRating(Rating rating)
        {            
            using (MXHEntities context = conn.GetContext())
            {
                if (!context.Ratings.Any(n=>n.CreateByAccountID == rating.CreateByAccountID && n.SystemObjectID == rating.SystemObjectID && n.SystemObjectRecordID == rating.SystemObjectRecordID))
                {
                    context.Ratings.AddObject(rating);
                    context.SaveChanges();
                    return true;
                }
                return false;
            }
        }


        public bool HasRateBefore(int systemObjectID, long systemObjectRecordID, int accountID)
        {
            bool result = false;
            using (MXHEntities context = conn.GetContext())
            {
                if (context.Ratings.Where(n => n.SystemObjectID == systemObjectID
                    && n.SystemObjectRecordID == systemObjectRecordID
                    && n.CreateByAccountID == accountID).Count() > 0) result = true;
            }
            return result;
        }


        public int[] TotalLikeNumber(int systemObjectID, long systemObjectRecordID)
        {
            int[] result = new int[] {0,0};
            using (MXHEntities context = conn.GetContext())
            {
                var rs = context.Ratings.Where(n => n.SystemObjectID == systemObjectID && n.SystemObjectRecordID == systemObjectRecordID);
                result[0] = rs.Where(n=>n.Type == 0).Count();
                result[1] = rs.Where(n => n.Type == 1).Count();
            }
            return result;
        }
    }
}
